/**
 * iWeb2GooglePages - Converts export iWeb content and uploads it to GPs.
 * Copyright (C) 2008 Will Droste
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>. 
 */
package org.iweb2gps;

import java.io.File;

import org.apache.commons.io.FileUtils;
import org.jdesktop.application.Application;
import org.jdesktop.application.Task;


@SuppressWarnings("unchecked")
public class ProcessTask extends Task {

    /**
     * @param application
     */
    public ProcessTask(Application application) {
        super(application);
    }

    /**
     * Convert and upload the files to Google Pages..
     * 
     * @see SwingWorker#doInBackground()
     */
    @Override
    protected Object doInBackground() throws Exception {
        AppPreferences prefs = new AppPreferences();
        // create the file object for src/dest
        File src = new File(prefs.getExportDirectory());
        File dest = new File(System.getProperty("java.io.tmpdir"), "iweb");
        // create the destination..
        FileUtils.deleteDirectory(dest);
        dest.mkdirs();
        // convert the file into the destination directory..
        IWebConverter converter = new IWebConverter(src, dest);
        converter.addListener(new IWebConverter.Listener() {
            /**
             * Set the progress messages..
             * 
             * @see Listener#processing(int, int, File)
             */
            public void processing(int idx, int total, File f) {
                setProgress(idx, 0, total * 2);
                setMessage("Converting file: " + f.getName());
            }
        });
        // clear the message queue..
        setMessage("");
        // convert the files from iweb to flat html..
        converter.convert();
        // send the files to Google Pages..
        String usr = prefs.getUserName();
        String pwd = prefs.getPassword();
        String domain = prefs.getDomain();
        Upload upload = new Upload(domain, usr, pwd);
        upload.login();
        File[] files = dest.listFiles();
        for (int i=0; i< files.length; i++) {
            upload.upload(files[i]);
            setProgress(i + files.length, 0, files.length * 2);
            setMessage("Uploading file: " + files[i].getName());
        }
        upload.logout();
        return null;
    }
}
